import { contest, contest_questions } from "@/models/contests";
import axios from "axios";
import { globalUrl, normalHeaders, verifyHeaders } from "./global";

async function toGetContests(): Promise<contest[] | null> {
    try {
        const res = await axios.get(globalUrl + 'sql/contests/gets?limit=100', {headers: normalHeaders});
        const data: contest[] = []
        if (res.status == 200 && res.data.code == 0){
            console.log('进入循环');
            for (let i = 0; i < res.data.contest_.length; i++){
                data.push({
                    key: res.data.contest_[i].id,
                    contestNo: res.data.contest_[i].contest_id,
                    titleName: res.data.contest_[i].name,
                    status: res.data.contest_[i].type == 1 ? '开放的' : '私立的',
                    startTime: res.data.contest_[i].start_time.split('T').join(' '),
                    endTime: res.data.contest_[i].end_time.split('T').join(' '),
                });
            }
            return data;
        } else {
            return null
        }
    } catch (error) {
        console.log(error);
        return null;
    }
}

async function toGetContestQuestions(contest_id: number): Promise<contest_questions[] | null>{
    try {
        const res = await axios.get(globalUrl + 'sql/questions/question', {params: {contest_id: contest_id}, headers: verifyHeaders});
        const data: contest_questions[] = [];
        if (res.status == 200 && res.data.code == 0) {
            for(let i = 0; i < res.data.question_.length; i++) {
                data.push({
                    index: res.data.question_[i].id,
                    questionNo: res.data.question_[i].question_id,
                    questionInside: String.fromCharCode('A'.charCodeAt(0) + res.data.question_[i].id - 1),
                    questionName: res.data.question_[i].name,
                    difficulty: res.data.question_[i].difficulty,
                });
            }
            console.log(data);
            return data;
        } else {
            return null;
        }
    } catch (error) {
        console.log(error);
        return null;
    }
}

export { toGetContests, toGetContestQuestions }